/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package domain.controllers;

import domain.Entity.EntityUsuario;
import domain.commands.RegistrarComando;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import managers.TareaManager;
import managers.UsuarioManager;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
import org.springframework.web.servlet.view.RedirectView;

/**
 *
 * @author jorge
 */
public class loginController extends SimpleFormController {

    
    UsuarioManager um = UsuarioManager.getInstance();
    TareaManager tm = TareaManager.getInstance();
    
    public loginController() {
        setCommandClass(RegistrarComando.class);
  }

    @Override
    protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command, org.springframework.validation.BindException errors) throws Exception {
       
        ModelAndView mav = new ModelAndView();
        HttpSession session = request.getSession(true);
        
        String gestor = null;
        RegistrarComando rc = (RegistrarComando) command;
        EntityUsuario eu = Login(rc.getNombre(),rc.getContrasena());
        
                if(eu!=null ){
                  
                  session.setAttribute( "nombre", eu.getNombre());
                  session.setAttribute( "contrasena", eu.getContrasena());
                  session.setAttribute("usuario",eu);
                 
        
                    if(eu.getTipo().equals("gestor")){
                       
                        gestor = "verdad";
                        session.setAttribute("gest", gestor);
                        mav.setView(new RedirectView("iniciar.htm"));
                        
                        
                        
                    }else if(eu.getTipo().equals("trabajador")){
                         
                        session.setAttribute("gest", gestor);
                        mav.setView(new RedirectView("iniciar.htm"));
                    }
                    
                }else{
                    
                    session.invalidate();
                    mav.setView(new RedirectView("error.htm"));
                }
        return mav;
        
        }
     
     private EntityUsuario Login(String nombre, String contrasena){  
         
         EntityUsuario eu = um.get(nombre);
         boolean enc = false;
         
         if(eu.getNombre() !=null){
             
             if(eu.getContrasena().equals(contrasena)){
                 
                 enc = true;
                 
             }         
         
         
         }
         if(enc){
         return eu;
         
         }else{
         
         return null;
         }
     }
 
     

}
